package com.xquant.pricing.utils;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class AESCryptUtil {
    private static final String sKey = "1985fdfaixff1314";
    private static Cipher encryptCipher = null;
    private static Cipher decryptCipher = null;
    static {
        try {
            byte[] raw = sKey.getBytes("utf-8");
            SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
            encryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            encryptCipher.init(Cipher.ENCRYPT_MODE, skeySpec);
            decryptCipher = Cipher.getInstance("AES/ECB/PKCS5Padding");//"算法/模式/补码方式"
            decryptCipher.init(Cipher.DECRYPT_MODE, skeySpec);
        }catch (Exception ex) {
            ex.printStackTrace();
//            System.out.println(ex.toString());
        }
    }
    // 加密
    public static String Encrypt(String sSrc){
        try {
            byte[] encrypted = encryptCipher.doFinal(sSrc.getBytes("utf-8"));
            return SysUtils.toHex(encrypted);
        }catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

    // 解密
    public static String Decrypt(String sSrc) {
        try {
            byte[] encrypted1 = SysUtils.toBytes(sSrc);
            try {
                byte[] original = decryptCipher.doFinal(encrypted1);
                String originalString = new String(original, "utf-8");
                return originalString;
            } catch (Exception e) {
                e.printStackTrace();
                return null;
            }
        } catch (Exception ex) {
            ex.printStackTrace();
            return null;
        }
    }

//    public static void main(String[] args) throws Exception {
//        String cSrc = RandomStringUtils.randomAlphanumeric(100);
//        java.text.SimpleDateFormat sdf = new java.text.SimpleDateFormat("yyyy-MM-dd HH:mm:ss SSS");
//        System.out.println(sdf.format(new Date()) + "开始");
//        for (int i = 0; i < 10; i++) {
//            // 需要加密的字串
//            // 加密
//            System.out.println(sdf.format(new Date()) + "开始加密" + cSrc);
//            String enString = AESCryptUtil.Encrypt(cSrc);
//            System.out.println(sdf.format(new Date()) + "加密后数据为" + enString);
//
//            // 解密
//            System.out.println(sdf.format(new Date()) + "开始解密" + enString);
//            String deString = AESCryptUtil.Decrypt(enString);
//            System.out.println(sdf.format(new Date()) + "解密后数据为" + deString);
//        }
//        System.out.println(sdf.format(new Date()) + "完成" +System.currentTimeMillis()/1000);
//    }
}
